#!/usr/bin/bash

path=`cd "$( dirname ${BASH_SOURCE[0]} )" && pwd`
cd $path
#初始化此脚本所需的变量
source config.sh

in_option=$1
alias=$2

if [[ $in_option == "" ]];then
	#配置安装方式
	echo ==================================
	echo "请选择安装方式："
	echo "1.为所有用户安装"
	echo "2.为当前用户安装"
	echo "3.命令激活（多个devenv共存时）"
	echo ==================================
	read -p "请选择：" in_option
fi

echo "配置环境变量,用来调用环境"
echo 'alias devenv='$dev_env/main.sh > $system_cache/export.txt
echo 'export PATH="'$system_bin':$PATH"' >> $system_cache/export.txt
echo 'export dev_env="'$dev_env'"' >> $system_cache/export.txt
source $bin/export.sh $system_cache/export.txt

if [[ $in_option == 1 ]];then
	profile=`grep "/system_bin/export.sh" /etc/profile`
	if [[ $profile != "" && `export dev_env` != "" ]];then
		echo "检测到您已经安装devenv,无法再使用1和2的安装方式。"
		echo "因为文件夹和文件名的不确定性，机器修改该文件可能会导致文件乱码，以至于无法进入系统。"
		echo "若您需要重新安装，请删除/etc/profile中的$profile后，执行source /etc/profile重试。谢谢。"
	fi
	source $bin/rely.sh
	if [[ $profile == "" || $profile != "$system_bin/export.sh" ]];then
		sudo echo source $system_bin/export.sh >> /etc/profile
	fi
	echo "安装完毕！如果您想继续在该窗口中使用devenv，之后记得执行source /etc/profile"
elif [[ $in_option == 2 ]];then
	bashrc=`grep "/system_bin/export.sh" ~/.bashrc`
	if [[ $bashrc != "" && `export dev_env` != "" ]];then
		echo "检测到您已经安装devenv,无法再使用1和2的安装方式。"
		echo "因为文件夹和文件名的不确定性，机器修改该文件可能会导致文件乱码，以至于无法进入系统。"
		echo "若您需要重新安装，请删除source ~/.bashrc中的$bashrc，执行source ~/.bashrc重试。谢谢。"
	fi
	source $bin/rely.sh 
	if [[ $bashrc == "" || $bashrc != "$system_bin/export.sh" ]];then
		echo source $system_bin/export.sh >> ~/.bashrc
	fi
	echo "安装完毕！如果您想继续在该窗口中使用devenv，之后记得执行source ~/.bashrc"
elif [[ $in_option == 3 ]];then
	if [[ $alias == "" ]];then
		#设置别名
		echo ==================================
		echo "请设置启动脚本命令："
		echo ==================================
		read -p "请输入：" alias
	fi
	#如果别名已经存在
	if [[ `alias | grep "alias $alias="` != "" ]];then
		#设置别名
		echo ==================================
		echo "别名已存在。请更换后重试！"
		echo "已存在的别名信息："
		alias
		echo ==================================
		exit
	fi
	cmd='alias '$alias'="source '$system_bin'/export.sh"'
	shell=`grep "$cmd" /etc/bash.bashrc`
	source $bin/rely.sh 
	if [[ $shell == "" || $shell != $cmd ]];then
		sudo sh -c "echo '$cmd' >> /etc/bash.bashrc"
	fi
	echo "安装完毕！请执行source /etc/bash.bashrc，之后记得执行$alias"
	echo "(每次创建新窗口需要使用该环境都需要执行$alias)"
else
	echo '没有这个选项'$in_option'！！！'
	exit
fi

#赋予执行权限
sudo chmod +x $system_bin/export.sh

